// This is a minimal preload script.
// It can be expanded later if needed to expose Node.js APIs
// to the renderer process 안전하게 using contextBridge.

const { contextBridge, ipcRenderer } = require('electron');

if (contextBridge && ipcRenderer) {
  try {
    contextBridge.exposeInMainWorld('electronAPI', {
      send: (channel, ...args) => ipcRenderer.send(channel, ...args),
      invoke: (channel, data) => ipcRenderer.invoke(channel, data),
      on: (channel, func) => {
        // Deliberately strip event as it includes `sender`
        ipcRenderer.on(channel, (event, ...args) => func(...args));
      },
      removeAllListeners: (channel) => ipcRenderer.removeAllListeners(channel),
      // New methods for store path
      getStorePath: () => ipcRenderer.invoke('get-store-path'),
      openStoreFolder: () => ipcRenderer.send('open-store-folder'),
      // 新增：获取SQLite数据库文件路径
      getSqliteDbPath: () => {
        console.log('[preload.js] 调用getSqliteDbPath');
        return ipcRenderer.invoke('get-sqlite-db-path');
      },
      // 新增：打开SQLite数据库所在文件夹
      openSqliteDbFolder: () => {
        console.log('[preload.js] 调用openSqliteDbFolder');
        return ipcRenderer.send('open-sqlite-db-folder');
      },
      // Methods for Pomodoro
      showPomodoroNotification: (notificationOptions) => {
        ipcRenderer.send('show-pomodoro-notification', notificationOptions);
      },
      // Methods for changing data path
      selectDataDirectory: () => ipcRenderer.invoke('select-data-directory'),
      setCustomDataPath: (newPath) => ipcRenderer.invoke('set-custom-data-path', newPath),
      // 新增：选择SQLite数据库路径
      selectSqliteDbPath: () => {
        console.log('[preload.js] 调用selectSqliteDbPath');
        return ipcRenderer.invoke('select-sqlite-db-path');
      },
      // 新增：设置SQLite数据库路径
      setSqliteDbPath: (path) => {
        console.log('[preload.js] 调用setSqliteDbPath, path:', path);
        return ipcRenderer.invoke('set-sqlite-db-path', path);
      },
      // Listener for when data path changed and restart is needed (no specific data needed for this simple listener)
      onDataPathChangedRestartRequired: (callback) => ipcRenderer.on('data-path-changed-restart-required', callback),
      // 新增：监听SQLite路径变更需要重启的事件
      onSqlitePathChangedRestartRequired: (callback) => ipcRenderer.on('sqlite-path-changed-restart-required', callback),
      
      // 新增：重启应用程序
      restartApp: (options) => ipcRenderer.send('restart-app', options),
      
      // SQLite 数据库操作方法 
      db: {
        // 加载所有数据
        loadAllData: () => ipcRenderer.invoke('db-load-all-data'),
        
        // 待办事项操作
        addTodo: (todo, source) => ipcRenderer.invoke('db-add-todo', { todo, source }),
        updateTodo: (todo) => ipcRenderer.invoke('db-update-todo', { todo }),
        deleteTodo: (todoId) => ipcRenderer.invoke('db-delete-todo', { todoId }),
        
        // 按日期待办事项操作
        getTodosByDate: () => ipcRenderer.invoke('db-get-todos-by-date'),
        getTodosForDateKey: (dateKey) => ipcRenderer.invoke('db-get-todos-for-date-key', { dateKey }),
        addTodoToDate: (todo, dateKey) => ipcRenderer.invoke('db-add-todo-to-date', { todo, dateKey }),
        deleteTodoFromDate: (todoId, dateKey) => ipcRenderer.invoke('db-delete-todo-from-date', { todoId, dateKey }),
        deleteBatchTodosFromDate: (todoIdsArray, dateKey) => ipcRenderer.invoke('db-delete-batch-todos-from-date', { todoIds: todoIdsArray, dateKey }),
        
        // 收件箱待办事项操作
        getInboxTodos: () => ipcRenderer.invoke('db-get-inbox-todos'),
        addInboxTodo: (todo) => ipcRenderer.invoke('db-add-inbox-todo', { todo }),
        deleteInboxTodo: (todoId) => ipcRenderer.invoke('db-delete-inbox-todo', { todoId }),
        deleteBatchInboxTodos: (todoIdsArray) => ipcRenderer.invoke('db-delete-batch-inbox-todos', { todoIdsArray }),
        
        // 归档待办事项操作
        getArchivedTodos: () => ipcRenderer.invoke('db-get-archived-todos'),
        archiveTodo: (todo, originalSource) => ipcRenderer.invoke('db-archive-todo', { todo, originalSource }),
        archiveBatchTodos: (todos, source) => ipcRenderer.invoke('db-archive-batch-todos', { todos, source }),
        deleteArchivedTodo: (todoId) => ipcRenderer.invoke('db-delete-archived-todo', { todoId }),
        deleteArchivedBatchTodos: (todoIds) => ipcRenderer.invoke('db-delete-archived-batch-todos', { todoIds }),
        
        // 其他待办事项操作
        moveTodoToDate: (todoId, newDateKey) => ipcRenderer.invoke('db-move-todo-to-date', { todoId, newDateKey }),
        
        // 设置操作
        getSettings: () => ipcRenderer.invoke('db-get-settings'),
        updateSettings: (settings) => ipcRenderer.invoke('db-update-settings', { settings }),
        
        // 数据迁移
        migrateFromStore: () => ipcRenderer.invoke('db-migrate-from-store'),
        
        // 提醒相关
        getReminders: () => ipcRenderer.invoke('db-get-all-reminders'),
        createReminder: (reminder) => ipcRenderer.invoke('db-create-reminder', { reminder }),
        updateReminder: (reminder) => ipcRenderer.invoke('db-update-reminder', { reminder }),
        deleteReminder: (reminderId) => ipcRenderer.invoke('db-delete-reminder', { reminderId }),
        updateReminderActive: (reminderId, isActive) => ipcRenderer.invoke('db-update-reminder-active', { reminderId, isActive })
      },
      // 通知相关
      showPomodoroNotification: (title, body) => ipcRenderer.send('show-pomodoro-notification', { title, body }),
      
      // 窗口导航
      navigateToReminder: () => ipcRenderer.send('navigate-to-reminder'),
      
      // 主题相关
      onApplyTheme: (callback) => ipcRenderer.on('apply-theme', (event, theme) => {
        console.log('[preload.js] 收到apply-theme事件，主题:', theme);
        callback(theme);
      }),
      
      // 数据路径相关
      getStorePath: () => ipcRenderer.invoke('get-store-path'),
      openStoreFolder: () => ipcRenderer.send('open-store-folder'),
      getSqliteDbPath: () => ipcRenderer.invoke('get-sqlite-db-path'),
      openSqliteDbFolder: () => ipcRenderer.send('open-sqlite-db-folder'),
      selectSqliteDbPath: () => ipcRenderer.invoke('select-sqlite-db-path'),
      setSqliteDbPath: (path) => ipcRenderer.invoke('set-sqlite-db-path', path)
    });
    console.log('[preload.js] electronAPI exposed to main world.');
  } catch (error) {
    console.error('[preload.js] Failed to expose electronAPI:', error);
  }
} else {
  console.warn('[preload.js] contextBridge or ipcRenderer not available. electronAPI not exposed.');
} 